package com.wu;

import java.util.Objects;

/**
 * 单链表
 */
public class SingleLinkList<E> {

    private int size = 0;

    private Node<E> first;

    private Node<E> last;

    public class Node<E>{

        private E data;

        private Node<E> pre;

        private Node<E> next;

        public Node(E data, Node<E> pre, Node<E> next) {
            this.data = data;
            this.pre = pre;
            this.next = next;
        }

        public E getData() {
            return data;
        }

        public void setData(E data) {
            this.data = data;
        }

        public Node<E> getPre() {
            return pre;
        }

        public void setPre(Node<E> pre) {
            this.pre = pre;
        }

        public Node<E> getNext() {
            return next;
        }

        public void setNext(Node<E> next) {
            this.next = next;
        }
    }

    public void add(E data){
        size ++;
        // 如果第一个节点为空，则最后一个节点和第一个节点都为新增节点
        if(first == null){
            first = new Node<>(data, null , null);
            last = first;
        }else{
            // 新增节点放最后
            Node newLastNode = new Node<>(data, last, null);
            last.setNext(newLastNode);
            last = newLastNode;
        }
    }

    public void removeLast(){
        Node<E> newLast = last.getPre();
        newLast.setNext(null);
        size--;
    }

    public int getSize(){
        return size;
    }

    public E getFirst() {
        return first.data;
    }

    public E getLast(){
        return last.data;
    }

    public void delete(E data){
        Node indexNode = first;
        // 循环查找与data equals相等的对象
        while(!Objects.equals(indexNode.getData(), data)){
            // 查找到最后都没有直接退出
            if(indexNode == last){
                return;
            }
            indexNode = indexNode.getNext();

        }
        /**
         *  删除查找到节点，将删除节点的pre节点的next指向删除节点的next,将删除节点的next节点的pre指向删除节点的pre
         */

        // 如果删除节点是第一个节点需要将pre置为null
        if(indexNode != first){
            indexNode.getPre().setNext(indexNode.getNext());
        }else{
            first = first.getNext();
            first.setPre(null);
        }
        // 如果删除节点是最后一个点需要将next置为null
        if(indexNode!=last){
            indexNode.getNext().setPre(indexNode.getPre());
        }else{
            last = last.getPre();
            last.setNext(null);
        }
        size--;
    }
}


